
import markdownIt from 'markdown-it'

const md = markdownIt()

md.core.ruler.push('custom-rule', state => {

  handle(state.tokens)

  function handle(tokens) {
    for (const token of tokens) {
      addClass(token, 'img', 'x-b-img')
      addClass(token, 'p', 'x-b-p')
      addClass(token, 'strong', 'x-b-strong')
      addClass(token, 'hr', 'x-b-hr')

      if (token.children?.length) handle(token.children)
    }
  }

  function addClass(token, tagName, ...classNames) {
    if (token.tag === tagName) {
      const c = token.attrGet('class') || ''
      token.attrSet('class', `${c ? c + ' ' : ''}${classNames.join(' ')}`)
    }
  }
})

const render = s => s && md.render(s)

export {
  render
}